package com.gsi.webstore.platform.storefront.pipelet.product;

import com.gsi.webstore.platform.storefront.capi.product.ProductBO;
import com.gsi.webstore.platform.storefront.internal.product.ProductBOImpl;
import com.intershop.beehive.core.capi.component.ComponentMgr;
import com.intershop.beehive.core.capi.domain.Domain;
import com.intershop.beehive.core.capi.naming.NamingMgr;
import com.intershop.beehive.core.capi.pipeline.Pipelet;
import com.intershop.beehive.core.capi.pipeline.PipeletExecutionException;
import com.intershop.beehive.core.capi.pipeline.PipelineDictionary;
import com.intershop.beehive.core.internal.app.AppContextUtil;
import com.intershop.beehive.xcs.capi.product.Product;
import com.intershop.component.catalog.capi.CatalogBOContext;
import com.intershop.component.catalog.capi.CatalogBOContextFactory;
import com.intershop.component.product.capi.ProductBOContext;
import com.intershop.component.product.capi.ProductBOContextFactory;

/**
 * Returns a new product business object instance based on the corresponding product 
 * instance on the persistence layer, specified by the 'Product' parameter.
 */
public class GetProductBO extends Pipelet
{

    public static final String DN_PRODUCT = "Product";
    public static final String DN_PRODUCT_BO = "ProductBO";
   
    /**
     * The pipelet's execute method is called whenever the pipelets gets
     * executed in the context of a pipeline and a request. The pipeline
     * dictionary valid for the currently executing thread is provided as a
     * parameter.
     * 
     * @param dict
     *            The pipeline dictionary to be used.
     * @throws PipeletExecutionException
     *             Thrown in case of severe errors that make the pipelet execute
     *             impossible (e.g. missing required input data).
     */
    public int execute(PipelineDictionary dict) throws PipeletExecutionException
    {
        Product product = (Product)dict.get(DN_PRODUCT);
        if (null == product)
        {
          throw new PipeletExecutionException("Mandatory input parameter 'Product' not available in pipeline dictionary.");
        }

        Domain domain = product.getDomain();

        ComponentMgr componentMgr = NamingMgr.getManager(ComponentMgr.class);
        ProductBOContextFactory contextFactory = componentMgr.getComponent(ProductBOContextFactory.COMPONENT_NAME);
        CatalogBOContextFactory catalogContextFactory = componentMgr.getComponent(CatalogBOContextFactory.COMPONENT_NAME);
        CatalogBOContext catalogContext = catalogContextFactory.createCatalogContext(AppContextUtil.getCurrentAppContext(), domain);
        ProductBOContext context = contextFactory.createProductContext(AppContextUtil.getCurrentAppContext(), domain, catalogContext);
                        
        ProductBO productBO = (ProductBO)context.getProductRepository().getProductByID(context, product.getUUID());

        dict.put(DN_PRODUCT_BO, productBO);

        return PIPELET_NEXT;
    }
}